package com.bucket.cloud.job.controller;

import com.bucket.cloud.common.core.controller.BaseController;
import com.bucket.cloud.common.core.model.Result;
import com.bucket.cloud.job.api.model.QuartzEntity;
import com.bucket.cloud.job.api.model.QuartzEntityPage;
import com.bucket.cloud.job.service.IJobService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/timer/job/")
@Slf4j
public class JobController extends BaseController {

    @Autowired
    private Scheduler scheduler;
    @Autowired
    private IJobService jobService;


    @ApiOperation(value = "新增定时任务", httpMethod = "POST")
    @PostMapping("add")
    public Result save(@RequestBody QuartzEntity quartz) {
        log.info("新增任务");
        try {
            //如果是修改  展示旧的 任务
            if (quartz.getOldJobGroup() != null) {
                JobKey key = new JobKey(quartz.getOldJobName(), quartz.getOldJobGroup());
                scheduler.deleteJob(key);
            }
            Class cls = Class.forName(quartz.getJobClassName());
            cls.newInstance();
            //构建job信息
            JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),
                    quartz.getJobGroup())
                    .withDescription(quartz.getDescription()).build();
            // 触发时间点
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger" + quartz.getJobName(), quartz.getJobGroup())
                    .startNow().withSchedule(cronScheduleBuilder).build();
            //交由Scheduler安排触发
            scheduler.scheduleJob(job, trigger);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed();
        }
        return Result.ok();
    }

    @PostMapping("list")
    @ApiOperation(value = "定时任务列表", httpMethod = "POST")
    public Object list(@RequestBody QuartzEntityPage quartz) {
        log.info("任务列表");
        return Result.ok().data(jobService.listQuartzEntity(quartz));
    }

    @RequestMapping("trigger")
    @ApiOperation(value = "触发定时任务", httpMethod = "POST")
    public Result trigger(@RequestBody QuartzEntity quartz) {
        log.info("触发任务");
        try {
            JobKey key = new JobKey(quartz.getJobName(), quartz.getJobGroup());
            scheduler.triggerJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return Result.failed();
        }
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping("pause")
    @ApiOperation(value = "停止定时任务", httpMethod = "POST")
    public Result pause(@RequestBody QuartzEntity quartz) {
        log.info("停止任务");
        try {
            JobKey key = new JobKey(quartz.getJobName(), quartz.getJobGroup());
            scheduler.pauseJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return Result.failed();
        }
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping("resume")
    @ApiOperation(value = "恢复定时任务", httpMethod = "POST")
    public Result resume(@RequestBody QuartzEntity quartz) {
        log.info("恢复任务");
        try {
            JobKey key = new JobKey(quartz.getJobName(), quartz.getJobGroup());
            scheduler.resumeJob(key);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return Result.failed();
        }
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping("delete")
    @ApiOperation(value = "移除定时任务", httpMethod = "POST")
    public Result delete(@RequestBody QuartzEntity quartz) {
        log.info("移除任务");
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(quartz.getJobName(), quartz.getJobGroup());
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(JobKey.jobKey(quartz.getJobName(), quartz.getJobGroup()));
            System.out.println("removeJob:" + JobKey.jobKey(quartz.getJobName()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed();
        }
        return Result.ok();
    }
}
